<template>
  <div class="app-container">
    <form-header />
    <el-form ref="form" :model="form" label-width="140px">
      <el-form-item label="活动名称">
        <el-input v-model="form.name" clearable placeholder="如：618活动大酬宾，最多15字" />
      </el-form-item>
      <el-form-item label="活动时间">
        <el-col :span="5">
          <el-date-picker v-model="form.beginTime" type="date" placeholder="选择开始日期" style="width: 100%;" :picker-options="pickerOptions" />
        </el-col>
        <el-col class="line" :span="1" style="text-align:center;">-</el-col>
        <el-col :span="5">
          <el-date-picker v-model="form.endTime" type="date" placeholder="选择结束日期" style="width: 100%;" :picker-options="pickerOptions" />
        </el-col>
      </el-form-item>
      <el-form-item label="有效时间">
        <el-radio v-model="form.effectiveTimeType" label="1">设置天数</el-radio>
        <el-radio v-model="form.effectiveTimeType" label="2">活动结束时间</el-radio>
        <el-input v-show="form.effectiveTimeType === '1'" v-model="form.effectiveTime" clearable placeholder="天数" />
        <el-date-picker v-show="form.effectiveTimeType === '2'" v-model="form.failureTime" type="date" placeholder="选择结束时间" style="width: 100%;" :picker-options="pickerOptions" />
      </el-form-item>
      <el-form-item label="地区选择">
        <el-radio v-model="form.areaType" label="1">部分地区</el-radio>
        <el-radio v-model="form.areaType" label="2">全国</el-radio>
        <div v-show="form.areaType === '1'">
          <el-select
            v-model="schoolForm.province"
            placeholder="请选择省份"
            @change="provinceChange"
          >
            <el-option
              v-for="item in addressOptions.province"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="schoolForm.city"
            placeholder="请选择城市"
            @change="cityChange"
          >
            <el-option
              v-for="item in addressOptions.city"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="schoolForm.area"
            placeholder="请选择市区"
            @change="areaChange"
          >
            <el-option
              v-for="item in addressOptions.area"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="schoolForm.street"
            placeholder="请选择街道( 可空 )"
            @change="streetChange"
          >
            <el-option
              v-for="item in addressOptions.street"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="满减券">
        <div v-for="(item, index) in form.fullDiscount" :key="index">
          <label style="font-weight: 400"><span class="star">*</span>优惠券金额（元）</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <label style="font-weight: 400">满XXX减XXX（元）</label><br>
          <el-input v-model="item.couponMoney" clearable placeholder="请输入" style="width:112px;" />
          <el-input v-model="item.money" clearable placeholder="请输入" style="width:120px;margin-left:33px;" />
          <el-button type="text" style="margin-left: 20px;" @click="fullDiscountDel(item, index)">删除</el-button><p />
        </div>
        <el-button type="primary" @click="addFullDiscount">添加满减券</el-button>
      </el-form-item>
      <el-form-item label="立减券">
        <div v-if="form.discountCoupon.length !== 0" class="clearfix">
          <div v-for="(item, index) in form.discountCoupon" :key="index" style="float: left; margin-right: 20px;">
            <label style="font-weight: 400"><span class="star">*</span>优惠券金额（元）</label><br>
            <el-input v-model="item.money" clearable placeholder="请输入" style="width:112px;" />
            <el-button type="text" @click="discountCouponDel(item, index)">删除</el-button>
          </div>
        </div>
        <p v-if="form.discountCoupon.length !== 0" />
        <el-button type="primary" @click="addDiscountCoupon">添加立减券</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { activityEdit, activityDetail } from '@/api/activity'
import {
  provinceList,
  cityList,
  areaList,
  streetList
} from '@/api/common'

export default {
  name: 'ActivityEdit',
  data() {
    return {
      form: {
        id: '',
        name: '',
        beginTime: null,
        endTime: null,
        effectiveTimeType: '1',
        effectiveTime: '',
        failureTime: null,
        areaType: '1',
        fullDiscount: [],
        discountCoupon: []
      },

      schoolForm: {
        province: '', // 省
        city: '',
        area: '',
        street: '',
        valueData: {
          detail: '',
          latLng: '',
          addressValue: '',
          province: '', // 省
          city: '', // 市
          region: '', // 区
          town: '', // 街道
          lat: '',
          lng: ''
        }
      },
      addressOptions: {
        province: [], // 省
        city: [],
        area: [],
        street: [],
        searchAdress: '',
        options: [],
        lat: '',
        lng: '',
        currentCity: ''
      },

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7// 如果没有后面的-8.64e7就是不可以选择今天的
        }
      }
    }
  },
  created() {
    this.form.id = this.$route.params['id']
    this.refresh()
  },
  mounted() {
    this.getData()
  },
  methods: {
    refresh() {
      activityDetail({ id: this.form.id }).then(response => {
        const data = response.data
        this.form.name = data.name
        this.form.beginTime = new Date(data.beginTime)
        this.form.endTime = new Date(data.endTime)
        if (data.effectiveTime !== null) {
          this.form.effectiveTimeType = '1'
          this.form.effectiveTime = data.effectiveTime / 1000 / 60 / 60 / 24
        } else {
          this.form.effectiveTimeType = '2'
          this.form.failureTime = new Date(data.failureTime)
        }
        if (
          (data.province === null || data.province === '') &&
          (data.city === null || data.city === '') &&
          (data.area === null || data.area === '') &&
          (data.town === null || data.town === '')
        ) {
          this.form.areaType = '2'
        } else {
          this.form.areaType = '1'
          this.schoolForm.valueData.province = this.schoolForm.province = data.province
          this.schoolForm.valueData.city = this.schoolForm.city = data.city
          this.schoolForm.valueData.region = this.schoolForm.area = data.area
          this.schoolForm.valueData.town = this.schoolForm.street = data.town
        }

        data.platformVolumes.forEach(element => {
          if (element['type'] === 1) {
            // eslint-disable-next-line no-useless-call
            this.form.discountCoupon.push.call(this.form.discountCoupon, { money: element['amount'] })
          }
          if (element['type'] === 2) {
            // eslint-disable-next-line no-useless-call
            this.form.fullDiscount.push.call(this.form.fullDiscount, { couponMoney: element['amount'], money: element['fullReduction'] })
          }
        })
      })
    },
    fullDiscountDel(item, index) {
      this.form.fullDiscount.splice(index, 1)
    },
    discountCouponDel(item, index) {
      this.form.discountCoupon.splice(index, 1)
    },
    addFullDiscount() {
      // eslint-disable-next-line no-useless-call
      this.form.fullDiscount.push.call(this.form.fullDiscount, { couponMoney: 0, money: 0 })
    },
    addDiscountCoupon() {
      // eslint-disable-next-line no-useless-call
      this.form.discountCoupon.push.call(this.form.discountCoupon, { money: 0 })
    },
    // 省
    provinceChange(v) {
      this.schoolForm.valueData.province = this.addressOptions.province.find(i => i.value === this.schoolForm.province).label
      this.schoolForm.city = null
      this.schoolForm.area = null
      this.schoolForm.street = null
      cityList({
        pid: v
      }).then(res => {
        this.addressOptions.city = res.data.map(i => {
          return {
            label: i.cityName,
            value: i.cityCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
    },
    // 市
    cityChange(v) {
      this.schoolForm.valueData.city = this.addressOptions.city.find(i => i.value === this.schoolForm.city).label
      this.schoolForm.area = null
      this.schoolForm.street = null
      areaList({
        pid: v
      }).then(res => {
        this.addressOptions.area = res.data.map(i => {
          return {
            label: i.areaName,
            value: i.areaCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
    },
    // 区
    areaChange(v) {
      this.schoolForm.valueData.region = this.addressOptions.area.find(i => i.value === this.schoolForm.area).label
      this.schoolForm.street = null
      streetList({
        pid: v
      }).then(res => {
        this.addressOptions.street = res.data.map(i => {
          return {
            label: i.streetName,
            value: i.streetCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
      const province = this.schoolForm.valueData.province
      const city = this.schoolForm.valueData.city
      const area = this.schoolForm.valueData.region
      console.log(`${province}${city}${area}`)
      this.schoolForm.valueData.addressRemarks = `${province}${city}${area}`
    },
    // 街道
    streetChange(v) {
      this.schoolForm.valueData.town = this.addressOptions.street.find(i => i.value === this.schoolForm.street).label
      const province = this.schoolForm.valueData.province
      const city = this.schoolForm.valueData.city
      const area = this.schoolForm.valueData.region
      const street = this.schoolForm.valueData.town
      this.schoolForm.valueData.addressRemarks = `${province}${city}${area}${street}`
    },
    getData() {
      // 省
      provinceList().then(res => {
        this.addressOptions.province = res.data.map(i => {
          return {
            label: i.provinceName,
            value: i.provinceCode,
            lat: i.lat,
            lng: i.lng
          }
        })
      })
    },
    submit() {
      const province = this.schoolForm.valueData.province
      const city = this.schoolForm.valueData.city
      const area = this.schoolForm.valueData.region
      if (this.form.name === '') {
        this.$message({ message: '请输入活动名称', type: 'error' })
        return
      }
      if (this.form.beginTime === null) {
        this.$message({ message: '请选择开始时间', type: 'error' })
        return
      }
      if (this.form.endTime === null) {
        this.$message({ message: '请选择结束时间', type: 'error' })
        return
      }

      if (this.form.effectiveTimeType === '1' && (this.form.effectiveTime.toString() === '0' || this.form.effectiveTime.toString() === '')) {
        this.$message({ message: '有效天数必须大于0', type: 'error' })
        return
      }

      if (this.form.effectiveTimeType === '2' && this.form.failureTime === null) {
        this.$message({ message: '请选择活动结束时间', type: 'error' })
        return
      }

      if (this.form.areaType === '1' && (province === '' || city === '' || area === '')) {
        this.$message({ message: '省市区为必填项', type: 'error' })
        return
      }

      // const hasFullDiscountMoney = this.form.fullDiscount.every(element => {
      //   return element.couponMoney.toString() !== '' && element.couponMoney.toString() !== '0'
      // })
      // if (this.form.fullDiscount.length === 0 || !hasFullDiscountMoney) {
      //   this.$message({ message: '满减券不能为空并且优惠券金额不能为空', type: 'error' })
      //   return
      // }

      // const hasDiscountCouponMoney = this.form.discountCoupon.every(element => element.money.toString() !== '' && element.money.toString() !== '0')
      // if (this.form.discountCoupon.length === 0 || !hasDiscountCouponMoney) {
      //   this.$message({ message: '立减券不能为空并且优惠券金额不能为空', type: 'error' })
      //   return
      // }

      this.goToSubmit()
    },
    goToSubmit() {
      const data = {}
      data['id'] = this.form.id
      data['name'] = this.form.name
      data['beginTime'] = this.form.beginTime.getTime()
      data['endTime'] = this.form.endTime.getTime()
      if (this.form.effectiveTimeType === '1') {
        data['effectiveTime'] = parseInt(this.form.effectiveTime.toString()) * 1000 * 60 * 60 * 24
      } else {
        data['failureTime'] = this.form.failureTime.getTime()
      }

      const province = this.schoolForm.valueData.province
      const city = this.schoolForm.valueData.city
      const area = this.schoolForm.valueData.region
      const town = this.schoolForm.valueData.town
      if (this.form.areaType === '1') {
        data['province'] = province
        data['city'] = city
        data['area'] = area
        data['town'] = town
      } else {
        data['province'] = ''
        data['city'] = ''
        data['area'] = ''
        data['town'] = ''
      }

      const fullDiscountList = this.form.fullDiscount.map(element => {
        return {
          type: '1',
          amount: element['couponMoney'],
          fullReduction: element['money']
        }
      })

      const discountCouponList = this.form.discountCoupon.map(element => {
        return {
          type: '0',
          amount: element['money']
        }
      })
      data['platformVolumes'] = [].concat(fullDiscountList, discountCouponList)

      activityEdit(data).then(response => {
        console.log(response)
        this.$message({ message: '提交成功', type: 'success' })
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.push({ name: 'ActivityList' })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.star {
	color:red;font-size:16px;
}
</style>
